import numpy as np
import pathlib

label_dir = pathlib.Path(r'F:\AIOPS\移动研究院\code\label-tool-cyp\label')
'''
将标注工具生成的txt文件转化为npy文件
'''

from glob import glob
import pathlib
import os
import numpy as np
import json

# data1_root = r'F:\AIOPS\基于迁移学习的多指标异常检测\data\Deepcluster'
# data2_root = r'F:\AIOPS\基于迁移学习的多指标异常检测\data\label_result_3000_5710'

if __name__ == '__main__':
    #     1.将所有文件名称换成相同的命名格式
    data1_file_list = glob(os.path.join(str(label_dir), '*.json'))
    label_npy = np.zeros((200, 96*14))
    # print(data1_file_list)
    for data_file in data1_file_list:
        f = pathlib.Path(data_file)
        f_name = f.name
        window_index = int(f_name.split('.')[0])
        if window_index >= 200:
            continue
        # print(window_index)
        with open(data_file, mode='r') as label_file:
            lines = label_file.readlines()
            start_label_info_list = []
            end_label_info_list = []
            # 提取button2，3的单击事件
            for line in lines:
                try:
                    label_info = json.loads(line)
                except Exception as e:
                    print(e)
                    print('error', data_file, line)
                    raise Exception
                if label_info['button_id'] == 2 and label_info['click_action'] == 'single':
                    start_label_info_list.append(label_info)
                if label_info['button_id'] == 3 and label_info['click_action'] == 'single':
                    end_label_info_list.append(label_info)
            if len(start_label_info_list) != len(end_label_info_list):
                print(f'标注有误,{data_file}')
                raise Exception
            # 改label_npy
            for start_label_info, end_label_info in zip(start_label_info_list, end_label_info_list):
                start_index = start_label_info['index']
                end_index = end_label_info['index']
                if end_index - start_index > 3:
                    label_npy[window_index, start_index:end_index + 1] = 1
    np.save('label_yidong_v2_200.npy', label_npy[:, 96*7:])
    print(np.sum(label_npy))